package com.hzchendou.blog.demo.resource.security.handler;

import com.hzchendou.blog.demo.common.model.vo.ResultVO;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * 路径访问受限
 *
 * @Date: 2022-05-25 13:51
 * @since: 1.0
 */
@Slf4j
public class PathAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("请求访问受限: {}, 错误信息: {}", request.getRequestURI(), accessDeniedException.getMessage());
        response.setStatus(HttpStatus.OK.value());
        ResultVO<String> result = ResultVO.fail("请求受限");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getWriter().print(result.toJson());
        response.getWriter().flush();
    }
}
